package com.hue.nio.day02.three;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/*
    NIO与零拷贝:
        1.mmap:适合小数据的拷贝，3次上下文切换和3次数据拷贝
        2.sendFile：适合大文件的拷贝，2次上下文的切换和2次数据拷贝
 */
public class Test01 {
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(7777));
            FileOutputStream fos = new FileOutputStream("E:\\mycode1\\netty\\src\\main\\java\\com\\hue\\nio\\day02\\three\\1.jpg");
            FileChannel fosChannel = fos.getChannel();
            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while (socketChannel.read(buffer) != 0) {
                    buffer.flip();
                    fosChannel.write(buffer);
                    buffer.clear();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
